package com.heima.comment.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.constants.message.HotArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.UserFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.behavior.dtos.NewBehaviorDTO;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.map.HashedMap;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    private GreenScan greenScan;

    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedissonClient redission;

    @Autowired
    private CommentHotService commentHotService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 保存评论
     *
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        //1. 校验参数
        ApUser user = AppThreadLocalUtils.getUser();
        //   校验是否登录
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2. 阿里云校验评论内容是否违规
        String content = dto.getContent();
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            //        过滤掉违规词汇：替换为**
            if (!scanResult.getSuggestion().equals("pass")) {
                content = scanResult.getFilteredContent();
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文本审核失败");
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "阿里云文本审核失败");
        }
        //敏感词校验，如存在替换为**
        //获取敏感词
        ResponseResult<List<String>> sensitivesResult = adminFeign.sensitives();
        if (!sensitivesResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, "远程调用失败");
        }
        List<String> sensitives = sensitivesResult.getData();
        //替换敏感词
        for (String sensitive : sensitives) {
            content = content.replace(sensitive, "**");
        }

        ResponseResult<ApArticle> articleResponse = articleFeign.findByArticleId(dto.getArticleId());
        if (articleResponse.getCode() == 503) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApArticle article = articleResponse.getData();
        //3. 远程查询当前登陆用户信息
        ResponseResult<ApUser> apUserResponse = userFeign.findUserById(user.getId());
        ApUser apUser = apUserResponse.getData();
        //4. 创建评论信息，并保存到mongo
        ApComment apComment = new ApComment();
        apComment.setAuthorId(apUser.getId());
        apComment.setAuthorName(apUser.getName());
        apComment.setArticleId(dto.getArticleId());
        apComment.setType((short) 0);
        apComment.setChannelId(article.getChannelId());
        apComment.setContent(content);
        apComment.setImage(apUser.getImage());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short) 0);
        apComment.setCreatedTime(new Date());
        mongoTemplate.insert(apComment);
        //*****添加文章评论-发送消息******
        NewBehaviorDTO mess = new NewBehaviorDTO();
        mess.setType(NewBehaviorDTO.BehaviorType.COMMENT);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, mess);
        log.info("评论行为 发送消息 ==>{}",JSON.toJSONString(mess));
        return ResponseResult.okResult();
    }

    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        //1. 参数校验
        //   评论id不能为空  operation必须为 0  或  1
        ApUser user = AppThreadLocalUtils.getUser();
        //   校验是否登录
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        RLock rLock = redission.getLock("likes-lock");
        rLock.lock();
        ApComment apComment;
        try {
            //2. 根据评论id查询评论数据， 为null返回错误信息
            apComment = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(dto.getCommentId())), ApComment.class);
            if (apComment == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论信息不存在");
            }
            //3. 如果是点赞操作 判断是否已经点赞
            ApCommentLike apCommentLike = mongoTemplate.findOne(Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("authorId").is(user.getId())), ApCommentLike.class);
            //   点过赞提示 请勿重复点赞
            if (dto.getOperation() == 0) {
                if (apCommentLike != null) {
                    CustException.cust(AppHttpCodeEnum.DATA_EXIST, "已经点过赞，请勿重复点赞");
                }
                //   未点过赞   保存点赞信息到mongo
                apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentId(dto.getCommentId());
                apCommentLike.setOperation((short) 0);
                mongoTemplate.insert(apCommentLike);
                //   并修改评论信息的点赞数量( + 1)
                apComment.setLikes(apComment.getLikes() + 1);
                apComment.setUpdatedTime(new Date());
                if (apComment.getLikes() >= 10 && apComment.getFlag() != (short) 1) {
                    commentHotService.hotCommentExecutor(apComment);
                } else {
                    mongoTemplate.save(apComment);
                }
            } else {
                //4. 如果是取消点赞操作
                //   删除点赞信息
                mongoTemplate.remove(Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("authorId").is(user.getId())), ApCommentLike.class);
                //
                //       并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
                if (apComment.getLikes() <= 0) {
                    CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "点赞数量出错");
                }
                apComment.setLikes(apComment.getLikes() - 1);
                apComment.setUpdatedTime(new Date());
                if (apComment.getFlag() == (short) 1) {
                    commentHotService.subHotCommentExecutor(apComment);
                } else {
                    mongoTemplate.save(apComment);
                }
                //
            }
        } finally {
            rLock.unlock();
        }
        //   返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        Map<String, Integer> map = new HashedMap();
        map.put("likes", apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    /**
     * 根据文章id查询评论列表
     *
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        //1. 参数校验
        //   校验size
        if (dto.getSize() == null || dto.getSize() <= 0) {
            dto.setSize(10);
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        //1. 根据条件查询评论列表
        List<ApComment> apComments = null;
        if (dto.getIndex().intValue() == 1) {
            apComments = mongoTemplate.find(Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("flag").is((short) 1)).with(Sort.by(Sort.Direction.DESC, "likes")), ApComment.class);
            List<ApComment> comments = mongoTemplate.find(Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("flag").is((short) 0).and("createdTime").lt(dto.getMinDate()))
                            .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                            .limit(dto.getSize() - apComments.size())
                    , ApComment.class);
            apComments.addAll(comments);
        }else {
            //   (文章id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
            apComments = mongoTemplate.find(Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("flag").is((short) 0).and("createdTime").lt(dto.getMinDate()))
                            .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                            .limit(dto.getSize())
                    , ApComment.class);
        }
        //2. 判断当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        //3. 如果未登录直接返回评论列表
        if (user == null) {
            return ResponseResult.okResult(apComments);
        }
        //4. 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
        //   (将所有ApComment 转成 ApCommentVO , 点过赞的operation设置为0)
        List<ApCommentVo> apCommentVos = new ArrayList<>();
        //   5.2 遍历评论列表
        for (ApComment apComment : apComments) {
            //ApCommentVo apCommentVo = ApCommentVo.builder().build();
            ApCommentVo apCommentVo = new ApCommentVo();
            try {
                //             将每一个评论  ApComment 转成 ApCommentVO
                BeanUtils.copyProperties(apCommentVo, apComment);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
            }
            //   5.1 根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
            //                 commentId  in    评论id列表   authorId = 登录人id
            ApCommentLike apCommentLike = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(apComment.getId())), ApCommentLike.class);
            //             其中  如果当前评论id在点赞记录中存在  设置operation字段为0  不存在不用做任何处理
            if (apCommentLike != null) {
                apCommentVo.setOperation((short) 0);
            }
            apCommentVos.add(apCommentVo);
        }
        return ResponseResult.okResult(apCommentVos);
    }
}
